package com.ggh.jinjilive.ui.live.adapter;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.ReplacementSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.ggh.jinjilive.R;
import com.ggh.jinjilive.databinding.ItemMallGoodsPointsBinding;
import com.ggh.jinjilive.databinding.ItemTvLiveMessageBinding;
import com.ggh.jinjilive.listener.AddItemOnClickListener;
import com.ggh.jinjilive.mobile.live.im.CustomMessage;
import com.ggh.jinjilive.mobile.live.im.MessageEntity;
import com.ggh.jinjilive.mobile.live.im.MessageMobile;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class TVLiveMessageAdapter  extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private Context mContext;
    private List<CustomMessage> customMessageList = new ArrayList<>();

    public TVLiveMessageAdapter(Context mContext){
        this.mContext = mContext;
    }

    public List<CustomMessage> getCustomMessageList(){
        return customMessageList;
    }

    public void setCustomMessage(CustomMessage customMessage){
        customMessageList.add(customMessage);
        notifyDataSetChanged();
    }




    private AddItemOnClickListener addItemOnClickListener;
    public void setAddItemOnClickListener(AddItemOnClickListener addItemOnClickListener) {
        this.addItemOnClickListener = addItemOnClickListener;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemTvLiveMessageBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.item_tv_live_message, parent, false);
        return new ItemViewHolder(binding);
    }

    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder recyclerViewholder,final int position) {
        ItemViewHolder holder = (ItemViewHolder)recyclerViewholder;
        CustomMessage customMessage = customMessageList.get(position);
        if(null != customMessage){
            MessageEntity messageEntity = new Gson().fromJson(customMessage.msg, MessageEntity.class);
            if(null != customMessage.cmd){
                switch (customMessage.cmd){
                    case "5"://弹幕消息
                    case "1"://文字消息
                        String title = messageEntity.getRank() + messageEntity.getNickname()+":" + messageEntity.getMessage();
                        SpannableString spannableStr = new SpannableString(title);
                        // 设置 tag。
                        spannableStr.setSpan(new TagSpan(messageEntity.getRank(),messageEntity.getLevel_img()), 0, String.valueOf(messageEntity.getRank()).length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                        spannableStr.setSpan(new ClickableSpan() {
                            @Override
                            public void onClick(View view) {
                                if(null != addItemOnClickListener){
                                    addItemOnClickListener.onSkipClicked(0,messageEntity.getNickname());
                                }
                            }

                            @Override
                            public void updateDrawState(@NonNull TextPaint ds) {
                                ds.setColor(mContext.getResources().getColor(R.color.md_blue_A700));//设置颜色
                                ds.setUnderlineText(false);//去掉下划线
                            }
                        }, title.indexOf(messageEntity.getNickname()),title.indexOf(messageEntity.getMessage()), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                        holder.binding.tvContent.setText(spannableStr);
                        break;
                    case "2"://进入直播间的提示
                        String title1 = messageEntity.getRank() + messageEntity.getNickname()+":" + "进入直播间";
                        SpannableString spannableStr1 = new SpannableString(title1);
                        spannableStr1.setSpan(new TagSpan(messageEntity.getRank(),messageEntity.getLevel_img()), 0, String.valueOf(messageEntity.getRank()).length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                        spannableStr1.setSpan(new ForegroundColorSpan(Color.parseColor("#FFCD35")), title1.indexOf("进入直播间"), title1.length(), 0);
                        spannableStr1.setSpan(new ClickableSpan() {
                            @Override
                            public void onClick(View view) {
                                if(null != addItemOnClickListener){
                                    addItemOnClickListener.onSkipClicked(0,messageEntity.getNickname());
                                }
                            }

                            @Override
                            public void updateDrawState(@NonNull TextPaint ds) {
                                ds.setColor(mContext.getResources().getColor(R.color.md_blue_400));//设置颜色
                                ds.setUnderlineText(false);//去掉下划线
                            }
                        }, title1.indexOf(messageEntity.getNickname()),title1.indexOf("进"), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                        holder.binding.tvContent.setText(spannableStr1);
                        break;
                    case "3"://退出直播间
                        String title2 = messageEntity.getRank() + messageEntity.getNickname()+":" + "退出直播间";
                        SpannableString spannableStr2 = new SpannableString(title2);
                        spannableStr2.setSpan(new TagSpan(messageEntity.getRank(),messageEntity.getLevel_img()), 0, String.valueOf(messageEntity.getRank()).length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                        spannableStr2.setSpan(new ForegroundColorSpan(Color.parseColor("#FFCD35")), title2.indexOf("退出直播间"), title2.length(), 0);
                        spannableStr2.setSpan(new ClickableSpan() {
                            @Override
                            public void onClick(View view) {
                                if(null != addItemOnClickListener){
                                    addItemOnClickListener.onSkipClicked(0,messageEntity.getNickname());
                                }
                            }

                            @Override
                            public void updateDrawState(@NonNull TextPaint ds) {
                                ds.setColor(mContext.getResources().getColor(R.color.md_blue_A700));//设置颜色
                                ds.setUnderlineText(false);//去掉下划线
                            }
                        }, title2.indexOf(messageEntity.getNickname()),title2.indexOf("退"), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                        holder.binding.tvContent.setText(spannableStr2);
                        break;
                    case "8"://直播礼物
                        MessageMobile messageMobile = new Gson().fromJson(messageEntity.getMessage(),MessageMobile.class);
                        String title8 = messageEntity.getRank() + messageEntity.getNickname()+ "送了" + messageMobile.getNumber() + "个" + messageMobile.getName();
                        SpannableString spannableStr8 = new SpannableString(title8);
                        spannableStr8.setSpan(new TagSpan(messageEntity.getRank(),messageEntity.getLevel_img()), 0, String.valueOf(messageEntity.getRank()).length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                        spannableStr8.setSpan(new ForegroundColorSpan(Color.parseColor("#FFCD35")), title8.indexOf("送了") + 2, title8.indexOf("个"), 0);
                        spannableStr8.setSpan(new ForegroundColorSpan(Color.parseColor("#FFCD35")), title8.indexOf(messageMobile.getName()), title8.length(), 0);
                        spannableStr8.setSpan(new ClickableSpan() {
                            @Override
                            public void onClick(View view) {
                                if(null != addItemOnClickListener){
                                    addItemOnClickListener.onSkipClicked(0,messageEntity.getNickname());
                                }
                            }

                            @Override
                            public void updateDrawState(@NonNull TextPaint ds) {
                                ds.setColor(mContext.getResources().getColor(R.color.md_blue_A700));//设置颜色
                                ds.setUnderlineText(false);//去掉下划线
                            }
                        }, title8.indexOf(messageEntity.getNickname()),title8.indexOf("送了"), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                        holder.binding.tvContent.setText(spannableStr8);
                        break;
                }
                holder.binding.tvContent.setMovementMethod(LinkMovementMethod.getInstance());
            }

        }
    }

    @Override
    public int getItemCount() {
        return null == customMessageList ? 0 : customMessageList.size();
    }


    class ItemViewHolder extends RecyclerView.ViewHolder {
        ItemTvLiveMessageBinding binding;
        public ItemViewHolder(@NonNull ItemTvLiveMessageBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
    }





    public class TagSpan extends ReplacementSpan {
        private final View view;

        private final int marginEnd = SizeUtils.dp2px(5);
        private final int mWidth;

        public TagSpan(int Rank,String Level_img) {
            view = LayoutInflater.from(mContext).inflate(R.layout.layout_live_tag, null);
            ImageView imgLiveLevel = view.findViewById(R.id.img_live_level);
            //级别图片
            Glide.with(imgLiveLevel).load(Level_img).into(imgLiveLevel);
            //级别
            TextView tv_live_level = view.findViewById(R.id.tv_live_level);
            tv_live_level.setText(Rank+"");
            int width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            int height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
            view.measure(width, height);
            // 获取宽度
            mWidth = view.getMeasuredWidth();
        }
        @Override
        public int getSize(@NonNull Paint paint, CharSequence charSequence, int i, int i1, @Nullable Paint.FontMetricsInt fontMetricsInt) {
            return mWidth + marginEnd;
        }

        @Override
        public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint){
            paint.setAntiAlias(true);
            Bitmap bmp = view2Bitmap(view);
            canvas.drawBitmap(bmp, x, y + paint.ascent(), paint);
        }
    }


    public static Bitmap view2Bitmap(final View view) {
        if (view == null) {
            return null;
        }
        boolean drawingCacheEnabled = view.isDrawingCacheEnabled();
        boolean willNotCacheDrawing = view.willNotCacheDrawing();
        view.setDrawingCacheEnabled(true);
        view.setWillNotCacheDrawing(false);
        Bitmap drawingCache = view.getDrawingCache();
        Bitmap bitmap;
        if (null == drawingCache || drawingCache.isRecycled()) {
            view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
            view.buildDrawingCache();
            drawingCache = view.getDrawingCache();
            if (null == drawingCache || drawingCache.isRecycled()) {
                bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.RGB_565);
                Canvas canvas = new Canvas(bitmap);
                view.draw(canvas);
            } else {
                bitmap = Bitmap.createBitmap(drawingCache);
            }
        } else {
            bitmap = Bitmap.createBitmap(drawingCache);
        }
        view.setWillNotCacheDrawing(willNotCacheDrawing);
        view.setDrawingCacheEnabled(drawingCacheEnabled);
        return bitmap;
    }
}